import request from '@/utils/request';
import { AutoapiParams } from './types';

// 刷新数据源
export function refreshDb() {
  return request({
    url: '/autoapi/refreshDb',
    method: 'get'
  });
}

// 插入数据
export function insert(entityName: string | string[], isAutoIncrement: boolean | string, data: any) {
  return request({
    url: `/autoapi/${entityName}/${isAutoIncrement}`,
    method: 'post',
    data
  });
}

// 更新数据
export function updateById(entityName: string | string[], id: number | string, data: any) {
  return request({
    url: `/autoapi/${entityName}/${id}`,
    method: 'put',
    data
  });
}

// 删除数据
export function deleteByIds(entityName: string | string[], ids: Array<number|string> | number | string) {
  const idsStr = Array.isArray(ids) ? ids.join(",") : ids;
  return request({
    url: `/autoapi/${entityName}/${idsStr}`,
    method: 'delete'
  });
}

// 获取数据
export function getById(entityName: string | string[], id: number | string) {
  return request({
    url: `/autoapi/${entityName}/${id}`,
    method: 'get'
  });
}

// 分页查询数据
export function pageQuery(entityName: string | string[], params: AutoapiParams) {
  if (params.where) {
    let where = params.where;
    if (typeof where !== 'string') {
      where = JSON.stringify(params.where);
    }
    // params.where = encodeURIComponent(where);
    params.where = where;
  }
  return request({
    url: `/autoapi/${entityName}`,
    method: 'get',
    params: params
  });
}

// 获取字段列表
export function getTableFields(entityName: string | string[]) {
  return request({
    url: `/autoapi/tableFields/${entityName}`,
    method: 'get'
  });
}
